package org.budo.validation.validator.impl;

import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Map;

import javax.validation.constraints.Size;

import org.budo.validation.exception.BudoSizeValidationException;
import org.budo.validation.validator.BudoValidator;

/**
 * @author lmw
 */
public class SizeValidator implements BudoValidator {
    public void validate(Annotation annotation, Integer parameterIndex, String parameterName, Object argumentValue) {
        if (null == argumentValue) {
            return;
        }

        Integer _size = size(argumentValue);

        Size size = (Size) annotation;
        if (null != _size && (_size > size.max() || _size < size.min())) {
            throw new BudoSizeValidationException(parameterIndex, parameterName, size, argumentValue);
        }
    }

    protected Integer size(Object argumentValue) {
        Integer _size = null;
        if (argumentValue instanceof String) {
            _size = ((String) argumentValue).length();
        } else if (argumentValue instanceof Collection) {
            _size = ((Collection) argumentValue).size();
        } else if (argumentValue instanceof Map) {
            _size = ((Collection) argumentValue).size();
        } else if (argumentValue.getClass().isArray()) {
            _size = ((Object[]) argumentValue).length;
        }
        return _size;
    }
}